import { createRouter, createWebHashHistory, RouterView } from "vue-router";
//导入vuex  解析出token  用于判断是否登陆
import store from "@/store";

//导入
const Layout = () => import("@/views/Layout");
const Home = () => import("@/views/Home");
// const Goods = () => import('@/views/goods')
import Category from "@/views/category";
import Sub from "@/views/category/sub";
import Goods from "@/views/goods";
import Login from "@/views/login";
import LoginCallback from "@/views/login/callback.vue";
import Cart from "@/views/cart";
import { h } from "vue";
const Checkout = () => import("@/views/member/pay/checkout.vue");
const XtxPayPage = () => import("@/views/member/pay");
const MemberLayout = () => import("@/views/member/Layout");
const MemberHome = () => import("@/views/member/home");
const MemberOrder = () => import("@/views/member/order");
const MemberDetail = () => import("@/views/member/order/detail");
//路由规则
const routes = [
  // 一级路由匹配规则
  {
    path: "/",
    component: Layout,
    children: [
      { path: "/", component: Home },
      { path: "/product/:id", component: Goods },
      { path: "/category/:id", component: Category },
      { path: "/category/sub/:id", component: Sub },
      { path: "/cart", component: Cart },
      { path: "/member/checkout", component: Checkout },
      { path: "/member/pay", component: XtxPayPage },
      {
        path: "/member",
        component: MemberLayout,
        children: [
          { path: "", component: MemberHome },
          // {path:'order',component:MemberOrder},
          // {path:'order/:id',component:MemberDetail}
          {
            path: "/member/order",
            component: { render: () => h(<RouterView></RouterView>) },
            children: [
              { path: "", component: MemberOrder },
              { path: ":id", component: MemberDetail },
            ],
          },
        ],
      },
    ],
  },
  { path: "/login", component: Login },
  { path: "/login/callback", component: LoginCallback },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { left: 0, top: 0 };
  },
});
router.beforeEach((to, from, next) => {
  const { token } = store.state.user.profile;
  if (!token && to.path.startsWith("/member")) {
    next("/login?redirectUrl=" + encodeURIComponent(to.fullPath));
  }
  next();
});
export default router;
